package com.dubbo.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;

public final class SpringMvcUtils {

    private SpringMvcUtils() {
    }

    public static String getServicePath(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Class<?> declaringClass = method.getDeclaringClass();

        RequestMapping classRequestMapping = AnnotationUtils.findAnnotation(declaringClass, RequestMapping.class);
        RequestMapping methodRequestMapping = AnnotationUtils.getAnnotation(method, RequestMapping.class);

        StringBuilder sb = new StringBuilder();

        if (classRequestMapping != null) {
            sb.append(getRequestMappingPath(classRequestMapping));
        }

        sb.append(getRequestMappingPath(methodRequestMapping));

        return sb.toString();
    }

    private static String getRequestMappingPath(RequestMapping requestMapping) {
        if (!ArrayUtils.isEmpty(requestMapping.path())) {
            return requestMapping.path()[0];
        }
        if (!ArrayUtils.isEmpty(requestMapping.value())) {
            return requestMapping.value()[0];
        }

        return "";
    }
}
